package com.lhg.controller;

import com.lhg.common.CommonResult;
import com.lhg.utils.dto.TokenResponse;
import com.lhg.entity.User;
import com.lhg.service.UserService;
import com.lhg.utils.JwtTokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
public class WebController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    private static final Logger logger = LoggerFactory.getLogger(WebController.class);

    @PostMapping("/login")
    public CommonResult<?> login(@RequestBody Map<String, String> loginData) {
        logger.info("Received login data: " + loginData);
        String username = loginData.get("username");
        String password = loginData.get("password");
        User user = userService.findByUsername(username);
// 模拟用户验证
        if (user.getPassword().equals(password)) {

            // 生成访问令牌和刷新令牌
            String accessToken = jwtTokenUtil.generateAccessToken(username);
            String refreshToken = jwtTokenUtil.generateRefreshToken(username);
            TokenResponse token_resp = new TokenResponse(accessToken,refreshToken);

            CommonResult<TokenResponse> result = CommonResult.success(token_resp);

            return result;
            //return CommonResult.success("登录成功");
        } else {
            return CommonResult.error(401, "用户名或密码错误");
        }
    }

    @PostMapping("/register")
    public CommonResult<?> register(@RequestBody Map<String, String> registerData) {
        logger.info("Received login data: " + registerData);
        String username = registerData.get("username");
        String password = registerData.get("password");
        userService.insertUser(username,password);
        return CommonResult.success("注册成功");
    }

    @GetMapping("/getInfo")
    public CommonResult<?> getUserProfile(@RequestHeader("Authorization") String authHeader) {
        User foundUser;
        try{
            foundUser = userService.findByAuthorization(authHeader);
        }catch(Exception e){
            return CommonResult.error(401,"jwt验证出错");
        }
        CommonResult<User> result = CommonResult.success(foundUser);
        return result;
    }

}
